package qj.tool.logger;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;

import qj.util.FileUtil4;


/**
 * Created by QuanLA Date: Mar 22, 2006 Time: 9:42:10 AM
 */
public class Logger {
	private LogPolicy policy;

	private static final boolean DEFAULT_SHOW_CONSOLE = true;
	
	public Logger(Class oclass) {
		policy = LogPolicy.getInstance(oclass, DEFAULT_SHOW_CONSOLE);
		if (policy.needAppendFile()) {
			FileUtil4.mkParentDirs(policy.getLogFile());
		}
	}

	public Logger(Class oclass, boolean showConsole) {
		policy = LogPolicy.getInstance(oclass, showConsole);
		if (policy.needAppendFile()) {
			FileUtil4.mkParentDirs(policy.getLogFile());
		}
	}

	public void info(String content) {
		content = policy.formatInfoContent(content);
		if (policy.needAppendFile()) {
			try {
				FileUtil4.appendToFile("\n" + content, policy.getLogFile());
			} catch (IOException e) {
			}
		}

		if (policy.isShowConsole())
			System.out.println(content);
	}

	public void debug(String content) {
		content = policy.formatDebugContent(content);
		if (policy.needAppendFile()) {
			try {
				FileUtil4.appendToFile("\n" + content, policy.getLogFile());
			} catch (IOException e) {
			}
		}
		
		if (policy.isShowConsole())
			System.out.println(content);
	}

	public void error(String content) {
		content = policy.formatErrorContent(content);
		if (policy.needAppendFile()) {
			try {
				FileUtil4.appendToFile("\n" + content, policy.getLogFile());
			} catch (IOException e) {
			}
		}
		
		if (policy.isShowConsole())
			System.out.println(content);
	}

	public void error(Exception e) {
		if (policy.needAppendFile()) {
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				PrintStream ps = new PrintStream(baos);
				e.printStackTrace(ps);
				ps.flush();
				ps.close();
				FileUtil4.appendToFile("\n" + policy.formatErrorContent(baos.toString()), policy.getLogFile());
			} catch (IOException e1) {
			}
		}
		e.printStackTrace(System.err);
	}
}
